package net.crowtheries.wirelessrouting;

import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
import java.util.HashMap;
import java.util.HashSet;
import net.crowtheries.wirelessrouting.messages.*;

import ptolemy.actor.TypedAtomicActor;
import ptolemy.data.RecordToken;
import ptolemy.data.StringToken;
import ptolemy.data.Token;
import ptolemy.data.expr.StringParameter;
import ptolemy.domains.wireless.kernel.WirelessIOPort;
import ptolemy.kernel.CompositeEntity;
import ptolemy.kernel.util.IllegalActionException;
import ptolemy.kernel.util.NameDuplicationException;

public class ProtocolManager extends TypedAtomicActor{
	public ProtocolManager(CompositeEntity container,String name) throws IllegalActionException, NameDuplicationException{
		super(container,name);
		_dstSeq=new HashMap<String, Integer>();
		_container=container;
		reqRoute=new WirelessIOPort(this,"reqRoute",true,false);
        toFlowHandler=new WirelessIOPort(this,"toFlowHandler",false,true);
	}
	
	//////Private vars////
	private int _localSeq;
	private HashMap<String, Integer> _dstSeq;
	private String _localIP;
	private CompositeEntity _container;
	private int _RREQID=0;
	
	///////PORTS//////
	public WirelessIOPort reqRoute;
    public WirelessIOPort toFlowHandler;
	
	public void initialize(){
		StringParameter localip=(StringParameter)this.getContainer().getAttribute("localIP");
		_localIP=localip.getValueAsString();
	}
	public void fire() throws IllegalActionException{
		/**
		 * If we receive a DSTIP from the RoutesManager, we make a RREQ 
		 */
		if(reqRoute.hasToken(0)){
			//Destination IP
			String dstIP=((StringToken)reqRoute.get(0)).stringValue();			
			//Destination SEQ
			//TODO:add the possibility to get the DSTSEQ from the cache _dstSeq
            //NOTE:dstSEQ=-1 indique qu'on n'a aucune info sur le seq number
			int dstSEQ=-1;

            RREQ request=new RREQ(_localIP,_localSeq,dstIP,dstSEQ,newRREQID());
            toFlowHandler.send(0, request.getRequestToken());

		}
	}

    private int newRREQID(){
        _RREQID++;
        if(_RREQID==65536)
            _RREQID=1;
        return _RREQID;
    }

}
